package cn.hfatec.shms.web.xc.xcJjbhz.service;

import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.base.BaseDao;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.system.user.model.User;
import cn.hfatec.shms.web.td.tdHzb.model.TdHzb;
import cn.hfatec.shms.web.td.tdHzb.model.TdHzbParams;
import cn.hfatec.shms.web.xc.xcJjbhz.dao.XcJjbhzDao;
import cn.hfatec.shms.web.xc.xcJjbhz.model.XcJjbhz;
import cn.hfatec.shms.web.xc.xcJjbhz.model.XcJjbhzParams;
import cn.hfatec.shms.web.xc.xcTjtj.model.XcTjtjParams;
import cn.hfatec.shms.web.xc.xcTjtj.model.XcTjtjView;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author hfatec
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Service("XcJjbhzService")
public class XcJjbhzService {

    public static final String BEAN_ID = "XcJjbhzService";

    //注入Dao层
    @Resource(name = "XcJjbhzDao")
    private XcJjbhzDao xcJjbhzDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;

    @Transactional
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询数据
     *
     * @param xcJjbhzParams
     * @param page
     */
    @Transactional
    public Table queryXcJjbhzTable(XcJjbhzParams xcJjbhzParams, Page page) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", xcJjbhzParams);
        if (xcJjbhzParams.getEntryStart() == null && xcJjbhzParams.getEntryEnd() == null) {
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            cal.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
              String  start = df.format(cal.getTime());
            cal.add(Calendar.MONTH, 1);//月增加1天
            cal.add(Calendar.DAY_OF_MONTH, -1);//日期倒数一日,既得到本月最后一天
              String  end = df.format(cal.getTime());
            xcJjbhzParams.setEntryStart(start);
            xcJjbhzParams.setEntryEnd(end);
        }
        return baseDao.queryTableByPage("queryXcJjbhz", params, page);
    }

    /**
     * 查询数据
     *
     * @param xcJjbhzParams
     *
     */
   @Transactional
    public XcJjbhz getXcJjbhzHj(XcJjbhzParams xcJjbhzParams) {

        return xcJjbhzDao.getXcJjbhzHj(xcJjbhzParams);
    }

    /**
     * 插入数据
     *
     * @param xcJjbhz
     */
    @Transactional
    public void saveXcJjbhz(XcJjbhz xcJjbhz, User user) {
        if (xcJjbhz.getId() != null) {
            XcJjbhz result = getXcJjbhz(xcJjbhz.getId());
            if (result != null) {
                xcJjbhz.setCreatTime(new Date());
                xcJjbhz.setCreatName(user.getLoginName());

                xcJjbhzDao.update(xcJjbhz);
            } else {
                xcJjbhz.setCreatTime(new Date());
                xcJjbhz.setCreatName(user.getLoginName());
                xcJjbhzDao.insert(xcJjbhz);
            }
        } else {
            xcJjbhz.setCreatTime(new Date());
            xcJjbhz.setCreatName(user.getLoginName());
            xcJjbhzDao.insert(xcJjbhz);
        }
    }

    /**
     * 插入数据
     *
     * @param xcJjbhz
     */
    @Transactional
    public void saveXcJjbhzs(XcJjbhz xcJjbhz, String[] ids, String[] userName, String[] jkxjJj, String[] jkxjYj, String[] tjJj, String[] tjGj,String[] ALp, String[] BLp, String[] CLp) {
        xcJjbhz = new XcJjbhz();
        if (ids != null) {
            for (int i = 0; i < ids.length; i++) {
                if (userName.length != 0) {
                    if (!userName[i].equals(""))
                        xcJjbhz.setUserName(userName[i]);
                    else
                        xcJjbhz.setUserName("180平台");
                }
                if (jkxjYj.length != 0) {
                    if (!jkxjYj[i].equals(""))
                        xcJjbhz.setJkxjYj(Integer.parseInt(jkxjYj[i]));
                    else
                        xcJjbhz.setJkxjYj(0);
                } else
                    xcJjbhz.setJkxjYj(0);

                if (CLp.length != 0) {
                    if (!CLp[i].equals(""))
                        xcJjbhz.setCLp(Integer.parseInt(CLp[i]));
                    else
                        xcJjbhz.setCLp(0);
                } else
                    xcJjbhz.setCLp(0);

                if (jkxjJj.length != 0) {
                    if (!jkxjJj[i].equals(""))
                        xcJjbhz.setJkxjJj(Integer.parseInt(jkxjJj[i]));
                    else
                        xcJjbhz.setJkxjJj(0);
                } else
                    xcJjbhz.setJkxjJj(0);
                if (tjJj.length != 0) {
                    if (!tjJj[i].equals(""))
                        xcJjbhz.setTjJj(Integer.parseInt(tjJj[i]));
                    else
                        xcJjbhz.setTjJj(0);
                } else
                    xcJjbhz.setTjJj(0);
                if (tjGj.length != 0) {
                    if (!tjGj[i].equals(""))
                        xcJjbhz.setTjGj(Integer.parseInt(tjGj[i]));
                    else
                        xcJjbhz.setTjGj(0);
                } else
                    xcJjbhz.setTjGj(0);

                if (ALp.length != 0) {
                    if (!ALp[i].equals(""))
                        xcJjbhz.setALp(Integer.parseInt(ALp[i]));
                    else
                        xcJjbhz.setALp(0);
                } else
                    xcJjbhz.setALp(0);
                if (BLp.length != 0) {
                    if (!BLp[i].equals(""))
                        xcJjbhz.setBLp(Integer.parseInt(BLp[i]));
                    else
                        xcJjbhz.setBLp(0);
                } else
                    xcJjbhz.setBLp(0);

                if (ids[i] != "") {

                    xcJjbhz.setId(Integer.parseInt(ids[i]));
                    xcJjbhzDao.update(xcJjbhz);
                } else {

                    xcJjbhz.setId(null);
                    xcJjbhzDao.insert(xcJjbhz);
                }
            }
        }

    }

    /**
     * 删除数据
     *
     * @param id
     */
    @Transactional
    public void deleteXcJjbhz(Integer id) {

        xcJjbhzDao.delete(id);
    }

    /**
     * 删除数据
     *
     * @param xcJjbhzList
     */
    @Transactional
    public void deleteXcJjbhzBatch(List<String> xcJjbhzList) {
        for (String id : xcJjbhzList) {
            deleteXcJjbhz(Integer.valueOf(id));
        }
    }

    /**
     * 根据ID获取数据
     *
     * @param entryStart
     * @param userName
     */
    @Transactional
    public XcJjbhz xcXcJjbhzHd(String entryStart,String userName ) {

        return xcJjbhzDao.getXcJjbhzHd(entryStart, userName);
    }

    /**
     * 根据ID获取数据
     *
     * @param id
     */
    @Transactional
    public XcJjbhz getXcJjbhz(Integer id) {

        return xcJjbhzDao.getXcJjbhzById(id);
    }

    /**
     * 根据ID获取数据
     *
     * @param entryStart
     */
    @Transactional
    public List getXcJjbhzList(String entryStart) {

        return xcJjbhzDao.getXcJjbhzByList(entryStart);
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    public String exportExcel(XcJjbhzParams xcJjbhzParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            List dataList =xcJjbhzDao.queryXcJjbhz(xcJjbhzParams);
            List nameList = new ArrayList();
            nameList.add("录入日期");
            nameList.add("个人报告领取");
            nameList.add("AK报告领取");
            nameList.add("TTM");
            nameList.add("健康宣教讲解");
            nameList.add("健康宣教引荐");
            nameList.add("体检报告讲解");
            nameList.add("体检报告跟进");
            nameList.add("A健康礼品");
            nameList.add("B健康礼品");
            nameList.add("C健康礼品");
            nameList.add("D健康礼品");
            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> vipTypeList = CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE);
        List<CodeInfo> overdueTypeList = CodeInfoCache.getCodeInfo(CodeType.OVERDUE_TYPE);

        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("现场精进表");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        XcJjbhz xcJjbhz = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            xcJjbhz = (XcJjbhz) fieldData.get(i);
            // 第四步，创建单元格，并设置值

            if (xcJjbhz.getEntryStart() == null) {
                row.createCell((short) 0).setCellValue("");
            } else {
                row.createCell((short) 0).setCellValue(xcJjbhz.getEntryStart());
            }
            if (xcJjbhz.getGrBgrq() == null) {
                row.createCell((short) 1).setCellValue("");
            } else {
                row.createCell((short) 1).setCellValue(xcJjbhz.getGrBgrq());
            }
            if (xcJjbhz.getAkBgrq() == null) {
                row.createCell((short) 2).setCellValue("");
            } else {
                row.createCell((short) 2).setCellValue(xcJjbhz.getAkBgrq());
            }
            if (xcJjbhz.getTtm() == null) {
                row.createCell((short) 3).setCellValue("");
            } else {
                row.createCell((short) 3).setCellValue(xcJjbhz.getTtm());
            }
            if (xcJjbhz.getJkxjJj() == null) {
                row.createCell((short) 4).setCellValue("");
            } else {
                row.createCell((short) 4).setCellValue(xcJjbhz.getJkxjJj());
            }
            if (xcJjbhz.getJkxjYj() == null) {
                row.createCell((short) 5).setCellValue("");
            } else {
                row.createCell((short) 5).setCellValue(xcJjbhz.getJkxjYj());
            }
            if (xcJjbhz.getTjJj() == null) {
                row.createCell((short) 6).setCellValue("");
            } else {
                row.createCell((short) 6).setCellValue(xcJjbhz.getTjJj());
            }
            if (xcJjbhz.getTjGj() == null) {
                row.createCell((short) 7).setCellValue("");
            } else {
                row.createCell((short) 7).setCellValue(xcJjbhz.getTjGj());
            }
            if (xcJjbhz.getAkBgrq() == null) {
                row.createCell((short) 8).setCellValue("");
            } else {
                row.createCell((short) 8).setCellValue(xcJjbhz.getAkBgrq());
            }
            if (xcJjbhz.getBLp() == null) {
                row.createCell((short) 9).setCellValue("");
            } else {
                row.createCell((short) 9).setCellValue(xcJjbhz.getBLp());
            }
            if (xcJjbhz.getCLp() == null) {
                row.createCell((short) 10).setCellValue("");
            } else {
                row.createCell((short) 10).setCellValue(xcJjbhz.getCLp());
            }
            if (xcJjbhz.getDLp() == null) {
                row.createCell((short) 11).setCellValue("");
            } else {
                row.createCell((short) 11).setCellValue(xcJjbhz.getDLp());
            }

        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }


        return wb;
    }


    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }
}